package com.webshop.servlet;

import com.webshop.Dao.PageDao;
import com.webshop.Dao.ProductDao;
import com.webshop.domain.Items;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/upload")
public class Upload extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("收到请求");

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String path = req.getServletContext().getRealPath("/img");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> list = upload.parseRequest(req);
            for (FileItem item: list){
                String imgName = item.getName();
                imgName = imgName.substring(imgName.indexOf('.'));
                imgName = "acdawsca"+imgName;
                System.out.println(imgName);
                InputStream is = item.getInputStream();
                FileOutputStream fos = new FileOutputStream(new File(path+"/"+imgName));
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len=(is.read(buffer)))>-1){
                    fos.write(buffer,0,len);
                }
                fos.close();
                is.close();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}


